<!-- 充值记录 -->
<script lang="ts" setup>
import { ref, reactive, watch } from "vue"
// Download
import { Search, Refresh, Download } from "@element-plus/icons-vue"
import { type FormInstance } from "element-plus"
import { usePagination } from "@/hooks/usePagination"
import { rechargeQuery, rechargeRecord } from "@/api/vouchercenter/index"
import { formatDateTime } from "@/utils/index"
import { shortcuts } from "@/utils/dateSet"

defineOptions({
  name: "rechargeRecord"
})
// 用户数据
import { useUserStore } from "@/store/modules/user"
const userStore = useUserStore()
const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
const searchFormRef = ref<FormInstance | null>(null)
const tableData = ref<any>()

// 搜索
const searchData = reactive<any>({
  data: "",
  state: "",
  orderNumber: "", // 订单号
  topUp: "" // 充值账号
})

const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    getRechargeQuery()
  }
  paginationData.currentPage = 1
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  getRechargeQuery()
}
// 查询
const total = ref()
const getRechargeQuery = () => {
  if (!searchData.data) {
    searchData.data = []
  }
  rechargeQuery({
    page: paginationData.currentPage,
    size: paginationData.pageSize,
    team: userStore.teamName,
    state: searchData.state,
    id: searchData.orderNumber,
    iphone: searchData.topUp,
    start: new Date(searchData.data[0]).getTime() || "",
    end: new Date(searchData.data[1]).getTime() || ""
  }).then((res: any) => {
    tableData.value = res.data.list
    total.value = res.data.total
    console.log(res, "123456")
  })
}
// 重新提交
const handleUpdate = (row: any) => {
  console.log(row, "重新提交")
}
/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getRechargeQuery, { immediate: true })

/** 订单下载 默认下载所有数据，查询后下载所有符合查询条件的数据*/
// const loading1 = ref<boolean>(false)
const downLoad = async () => {
  if (!searchData.data) {
    searchData.data = []
  }
  loading.value = true
  await rechargeRecord({
    team: userStore.teamName,
    state: searchData.state,
    id: searchData.orderNumber,
    iphone: searchData.topUp,
    start: new Date(searchData.data[0]).getTime() || "",
    end: new Date(searchData.data[1]).getTime() || ""
  })
    .then((res: any) => {
      const blob = new Blob([res.data], {
        type: "application/xlsx;charset=utf-8"
      })
      // console.log(res)
      const downloadElement = document.createElement("a")
      const href = window.URL.createObjectURL(blob)
      downloadElement.href = href
      downloadElement.download = "充值记录.xlsx"
      document.body.appendChild(downloadElement)
      downloadElement.click()
      window.URL.revokeObjectURL(href)
    })

    .finally(() => {
      loading.value = false
    })
}

//下载话费记录相关
import { downLoadPb } from "@/api/order"
const downPhoneBill = () => {
  if (!searchData.data) {
    searchData.data = []
  }
  loading.value = true
  downLoadPb({
    teamName: userStore.teamName,
    startDate: new Date(searchData.data[0]).getTime() || "",
    endDate: new Date(searchData.data[1]).getTime() || ""
  })
    .then((res: any) => {
      const blob = new Blob([res.data], {
        type: "application/xlsx;charset=utf-8"
      })
      // console.log(res)
      const downloadElement = document.createElement("a")
      const href = window.URL.createObjectURL(blob)
      downloadElement.href = href
      downloadElement.download = "话费补贴总表.xlsx"
      document.body.appendChild(downloadElement)
      downloadElement.click()
      window.URL.revokeObjectURL(href)
    })
    .finally(() => {
      loading.value = false
    })
}

// 时间
const defaultTime1: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 0)]
</script>

<template>
  <div class="app-container">
    <!-- 搜索功能 -->
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="data" label="日期">
          <el-date-picker
            v-model="searchData.data"
            type="datetimerange"
            range-separator="到"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :default-time="defaultTime1"
            :shortcuts="shortcuts"
          />
        </el-form-item>

        <el-form-item prop="state" label="状态">
          <el-select v-model="searchData.state" clearable placeholder="请选择状态">
            <el-option label="下单失败" value="下单失败" />
            <el-option label="下单成功" value="下单成功" />
            <el-option label="充值失败" value="充值失败" />
            <el-option label="充值成功" value="充值成功" />
            <el-option label="已经退款" value="已经退款" />
            <el-option label="处理中" value="处理中" />
          </el-select>
        </el-form-item>
        <el-form-item prop="orderNumber" label="订单号">
          <el-input v-model.trim="searchData.orderNumber" placeholder="请输入订单号" />
        </el-form-item>
        <el-form-item prop="topUp" label="充值账号">
          <el-input v-model.trim="searchData.topUp" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 表格内容 -->
    <el-card v-loading="loading">
      <div class="toolbar-wrapper">
        <el-tooltip content="下载">
          <el-button type="primary" :icon="Download" circle @click="downLoad" />
        </el-tooltip>
        <el-button style="vertical-align: top" class="ml-3" type="warning" :icon="Download" @click="downPhoneBill">
          下载话费总表
        </el-button>
      </div>
      <div class="table-center">
        <el-table :data="tableData" style="width: 100%">
          <el-table-column label="充值时间" width="180" align="center">
            <template #default="scope">
              {{ formatDateTime(scope.row.date) }}
            </template>
          </el-table-column>
          <el-table-column label="完成时间" width="180" align="center">
            <template #default="scope">
              <text v-if="scope.row.time !== null"> {{ formatDateTime(scope.row.time) }}</text>
            </template>
          </el-table-column>
          <el-table-column prop="team" label="团队名" width="180" align="center" />
          <el-table-column prop="userName" label="账户名" align="center" />
          <el-table-column prop="id" label="订单号" width="180" align="center" />
          <el-table-column prop="amount" label="提交金额(元)" align="center" />
          <el-table-column prop="realityAmount" label="实际金额(元)" align="center" />
          <el-table-column prop="phone" label="充值账号" align="center" />
          <el-table-column prop="state" label="状态" align="center" />
          <el-table-column prop="note" label="原因" align="center" />
          <el-table-column fixed="right" label="操作" width="100" align="center">
            <template #default="scope">
              <el-button
                v-if="scope.row.state == '充值失败' || scope.row.state == '已经退款' || scope.row.state == '下单失败'"
                type="primary"
                text
                bg
                size="small"
                @click="handleUpdate(scope.row)"
                >重新提交</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页器 -->
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- <div class="loading" v-loading="loading1" v-if="loading1">下载中...</div> -->
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
}
.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}
.table-center {
  margin-bottom: 20px;
}
.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>
